//
//  WKWebViewVC.m
//  CEX
//
//  Created by xiebin on 2018/1/4.
//  Copyright © 2018年 mingthink. All rights reserved.
//

#import "WKWebViewVC.h"
@interface WKWebViewVC ()<WKNavigationDelegate,WKUIDelegate>
{
    WKWebViewConfiguration *wkWebConfig;
}
@end

@implementation WKWebViewVC

- (void)viewDidLoad {
    [super viewDidLoad];
     [self initWebView];
}
#pragma mark -------------初始化webView
- (void)initWebView {
    wkWebConfig = [[WKWebViewConfiguration alloc] init];
    // 自适应屏幕宽度js 允许页面缩放
    NSString *autoWidthjsStr = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    
    WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:autoWidthjsStr injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//    WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:cookiejsStr injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
//
    [wkWebConfig.userContentController  addUserScript:wkUserScript];
//    [wkWebConfig.userContentController  addUserScript:cookieScript];
    
    mainWebV = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) configuration:wkWebConfig];
    [self.view addSubview:mainWebV];
    mainWebV.sd_layout.topSpaceToView(self.view,NAVBAR_HEIGH).leftSpaceToView(self.view,0).rightSpaceToView(self.view,0).bottomSpaceToView(self.view, 0);
    mainWebV.navigationDelegate = self;
    mainWebV.UIDelegate=self;
    mainWebV.userInteractionEnabled=YES;
    
    //_webView.scalesPageToFit = YES;
    //NSURL *url = [[NSBundle mainBundle] URLForResource:@"ExampleApp" withExtension:@"html"];
    if (self.urlStr && self.urlStr.length > 0){
        NSURL *url = [NSURL URLWithString:self.urlStr];
        DeLog(@"url === %@",url);
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        //[request addValue:[self getCookieValue] forHTTPHeaderField:@"Cookie"];
        [mainWebV loadRequest:request];
        //        NSString *path=[[NSBundle mainBundle] pathForResource:@"abc1" ofType:@"html"];
        //        [webv_main loadHTMLString:[NSString stringWithContentsOfURL:[NSURL fileURLWithPath:path] encoding:NSUTF8StringEncoding error:nil] baseURL:nil];
    }
    //[mainWebV addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];//监测webview的title
}
#pragma mark-----------WKWebView代理
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSURL *url = navigationAction.request.URL;
    //DeLog(@"-------requestURL2:%@",url);
    //NSString *scheme = [url scheme];
    
    //NSURL *url=[NSURL URLWithString:_urlStr];
        decisionHandler(WKNavigationActionPolicyAllow);
}
-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    BOOL isCanBack=[webView canGoBack];
    DeLog(@"---iscanBack2:%d",isCanBack);
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
    //    NSArray *cookies =[NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];
    //    //读取wkwebview中的cookie 方法1
    //    for (NSHTTPCookie *cookie in cookies) {
    //        //        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    //        NSLog(@"wkwebview中的cookie:%@", cookie);
    //
    //    }
    //读取wkwebview中的cookie 方法2 读取Set-Cookie字段
    NSString *cookieString = [[response allHeaderFields] valueForKey:@"Set-Cookie"];
    //NSLog(@"wkwebview中的cookie:%@", cookieString);
    
    NSInteger statusCode=((NSHTTPURLResponse *)navigationResponse.response).statusCode;
    //DeLog(@"-------statusCode:%ld",statusCode);
    //if (statusCode == 200) {
    //        decisionHandler (WKNavigationResponsePolicyAllow);
    //    }else {
    //       decisionHandler(WKNavigationResponsePolicyAllow);
    //    }
    decisionHandler(WKNavigationResponsePolicyAllow);
    
}
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
   [self showWaitWithTitle:@"正在加载..."];
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
        [self stopWait];
    //    [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError * _Nullable error) {
    //        DeLog(@"-----agent2:%@",result);
    //    }];
    //    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    //    DeLog(@"-----cookie2:%@",cookies);
    //    [webView evaluateJavaScript:@"document.title" completionHandler:^(id result, NSError * _Nullable error) {
    //self.title=result;
    //DeLog(@"-----title:%@",result);
    //}];
    
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
        [self stopWait];
}
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    completionHandler();
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    //    DLOG(@"msg = %@ frmae = %@",message,frame);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
    
    [self presentViewController:alertController animated:YES completion:nil];
}
////监测webview的title设置为导航title
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
//    if ([keyPath isEqualToString:@"title"]){
//        if (object == mainWebV) {
//            self.title = mainWebV.title;
//        }
//        else{
//            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
//        }
//    }
//    else {
//        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
//    }
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
